package com.echo.yiwei.fiter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.echo.util.GsonUtil;
import com.echo.util.ParamesList;
import com.echo.util.StringEchoUtil;
import com.echo.util.ValidateUtil;

/**
 * 通过注解的形式声明一个过滤器  过滤器执行的顺序 通过filterName区别
 * @author tangsixiang
 *
 */
@WebFilter(filterName="fitler2" ,urlPatterns={"/userInterface/*","/productInterface/*"})
public class ParamesFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
	     HttpServletRequest requestHTTP = (HttpServletRequest) request;
	     HttpServletResponse responseHTTP =   (HttpServletResponse) response;
		 boolean flag=false;
		Map<String,String> map= (Map<String, String>) requestHTTP.getAttribute("paramesMap");
		  try {
			   /***
			    * 对请求参数进行校验
			    */
			   if(ParamesList.methodes.containsKey(requestHTTP.getPathInfo().replace("/", ""))){
				   String methodParamArray=ParamesList.methodes.get(requestHTTP.getPathInfo().replace("/", ""));
				  flag=	ValidateUtil.validateMethodParames(map, methodParamArray.split(";"));
				}else{
					flag=	ValidateUtil.validateCommonParames(map);
				}
		
	}catch (Exception e){
		e.printStackTrace();
	}
		   if(flag){
			   chain.doFilter(request, response);  
		   }
		   else{
			    map.put("mes","参数不合法！不支持服务");
			   StringEchoUtil.toClient(GsonUtil.toJson(map), responseHTTP);   
		   }
}
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
